package downloader.util;


import downloader.thread.DownloadThread;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadUtil {
	private static DownloadThread[] threads;
	private static long length;


	public static void download(String path, String savePath, int threadNum) throws Exception {
		threads = new DownloadThread[threadNum];
		URL url = new URL(path);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setConnectTimeout(5000);
		con.setRequestMethod("GET");
		if (con.getResponseCode() == 200) {
			length = con.getContentLength();
			String filePath = savePath + getFileName(path);
			File file = new File(filePath);
			RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
			accessFile.setLength(length);
			accessFile.close();

			long block = length % threadNum == 0 ? length / threadNum : length / threadNum + 1;

			for (int threadId = 0; threadId < threadNum; threadId++) {
				threads[threadId] = new DownloadThread(threadId, block, url, file);
				threads[threadId].start();
			}
		}
	}

	public static boolean isDownloadFinished() {
		for (DownloadThread thread : threads) {
			if (!thread.isFinished())
				return false;
		}
		return true;
	}

	private static String getFileName(String path) {
		int index = path.lastIndexOf("/");
		return path.substring(index + 1);
	}

	static DownloadThread[] getThreads() {
		return threads;
	}

	static long getLength() {
		return length;
	}
}
